package com.trytech.mongoocrawler.client.transport.http;

import com.trytech.mongoocrawler.client.transport.http.cookie.HttpCookiesHolder;
import com.trytech.mongoocrawler.client.transport.http.cookie.HttpCookiesManager;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * Created by coliza on 2017/7/31.
 */
public class HttpRequestProtocol extends HttpProtocol {
    private String method;//请求方法
    private URL url;//url
    private String version;//版本
    private HttpRequestHeader header;//请求头

    private HttpRequestProtocol(){
        this.version = "HTTP/1.1";
        this.header = new HttpRequestHeader();
    }

    public static HttpRequestProtocol newInstance(){
        return new HttpRequestProtocol();
    }
    public String getMethod() {
        return method;
    }

    public HttpRequestProtocol setMethod(String method) {
        this.method = method;
        return this;
    }

    public URL getUrl() {
        return url;
    }

    public HttpRequestProtocol setUrl(URL url) {
        this.url = url;
        return this;
    }

    public String getVersion() {
        return version;
    }

    public HttpRequestProtocol setVersion(String version) {
        this.version = version;
        return this;
    }

    public HttpRequestHeader getHeader() {
        return header;
    }

    public HttpRequestProtocol setHeader(HttpRequestHeader header) {
        this.header = header;
        return this;
    }

    public URLConnection getConnection(CrawlerHttpRequest request){
        if(url == null)return null;
        try {
            URLConnection conn = null;
            String protocol = url.getProtocol();
            if("http".equalsIgnoreCase(protocol)) {
                conn = (HttpURLConnection) url.openConnection();
            }else{
                conn = (HttpsURLConnection) url.openConnection();
            }
            //处理请求头
            conn.addRequestProperty("encoding",HttpProtocol.ENCODING);
            if(header != null){
                Map<String, String> parameterMap = header.toMap();
                for(String key:parameterMap.keySet()){
                    conn.addRequestProperty(key,parameterMap.get(key));
                }
            }
            //添加cookie信息
            HttpCookiesHolder cookiesHolder = HttpCookiesManager.getCookiesHolder(request.getSessionId(), HttpCookiesHolder.DEFAULT_PATH);
            if(cookiesHolder != null) {
                conn.addRequestProperty("Cookie",cookiesHolder.toCookieString());
            }
            conn.setDoInput(true);
            conn.setDoOutput(true);
            return conn;
        } catch (IOException e) {
            return null;
        }

    }
}
